package com.tuanbiao.ui.upload;

import android.content.Context;
import android.content.Intent;
import android.view.KeyEvent;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.abiao.lib_utils.ViewUtils;
import com.hzjq.data.entity.BlastEntity;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.tuanbiao.R;
import com.tuanbiao.base.mvp.BasePresenterActivity;
import com.tuanbiao.controllers.UploadDataController;
import com.tuanbiao.databinding.ActivityUploadDataBinding;
import com.tuanbiao.dialog.UploadErrorDialog;
import com.tuanbiao.dialog.WaitDialog;
import com.tuanbiao.events.UploadDataDetailsEvent;
import com.tuanbiao.keyevent.KeyEventHelper;
import com.tuanbiao.keyevent.listener.OnKeyDownListener;
import com.tuanbiao.models.UploadDataModel;
import com.tuanbiao.presenter.UploadDataPresenter;
import com.tuanbiao.ui.log.BlastBackupActivity;
import com.tuanbiao.utils.ClickUtil;
import com.tuanbiao.utils.LibCollections;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

public class UploadDataActivity extends BasePresenterActivity<UploadDataPresenter, ActivityUploadDataBinding> implements UploadDataController.View {
    private ActivityResultLauncher<Intent> activityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
            result -> {
                binding.srlContent.autoRefresh();
            });
    private UploadDataAdapter uploadDataAdapter;
    private WaitDialog.Builder waitDialogBuilder;

    public static void start(Context context) {
        Intent starter = new Intent(context, UploadDataActivity.class);
        context.startActivity(starter);
    }

    @Override
    protected ActivityUploadDataBinding getBindingView() {
        return ActivityUploadDataBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initView() {
        binding.ivToolbarBack.setOnClickListener(getBackListener());
        binding.btnBackup.setOnClickListener(view -> {
            if (ClickUtil.isFastClick()) {
                return;
            }
            BlastBackupActivity.start(getActivity());
        });
        binding.srlContent.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mPresenter.refresh();
            }

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPresenter.loadMore();
            }
        });
        uploadDataAdapter = new UploadDataAdapter();
//        uploadDataAdapter.setOnItemClickListener((adapter, view, position) -> {
//            BlastEntity info = (BlastEntity) adapter.getItem(position);
//            if (null != info) {
//                EventBus.getDefault().postSticky(new UploadDataDetailsEvent(info));
//                UploadDataDetailsActivity.start(getActivity());
//            }
//        });
        uploadDataAdapter.addChildClickViewIds(R.id.btn_details, R.id.btn_upload, R.id.btn_re_upload);
        uploadDataAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (ClickUtil.isFastClick()) {
                return;
            }
            BlastEntity info = (BlastEntity) adapter.getItem(position);
            if (null != info) {
                if (view.getId() == R.id.btn_details) {
                    EventBus.getDefault().postSticky(new UploadDataDetailsEvent(info));
                    activityResultLauncher.launch(UploadDataDetailsActivity.createIntent(getActivity()));
                } else if (view.getId() == R.id.btn_upload) {
                    showErrorUploadSelectDialog(position,info);
                } else if (view.getId() == R.id.btn_re_upload) {
                    showErrorUploadSelectDialog(position,info);
                }
            }
        });
        binding.rvContent.setLayoutManager(new LinearLayoutManager(getActivity()));
        binding.rvContent.setAdapter(uploadDataAdapter);
        binding.btnCommit.setOnClickListener(v -> {
            if (ClickUtil.isFastClick()) {
                return;
            }
            mPresenter.uploadAll();
        });
        binding.srlContent.autoRefresh();
    }


    private void showErrorUploadSelectDialog(int position,BlastEntity info){
        if(info.getErrorCount() > 0) {
            UploadErrorDialog.show(getActivity(), "当前记录中包含"+info.getErrorCount()+"发异常雷管信息，是否需要全部上传？",
                    new UploadErrorDialog.OnUploadMenuItemClickListener() {

                        @Override
                        public void onUploadClick(boolean isAll) {
                            mPresenter.upload(position,isAll, info);
                        }
                    });
        } else  {
            mPresenter.upload(position,true, info);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        KeyEventHelper.getInstance().checkUploadDataKeyDown(keyCode, new OnKeyDownListener() {

            @Override
            public void onSuccess() {
                BlastBackupActivity.start(getActivity());
            }
        });
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected UploadDataPresenter createPresenter() {
        return new UploadDataPresenter(new UploadDataModel(), this);
    }

    @Override
    public void setItems(List<BlastEntity> blastEntities) {
        binding.srlContent.finishRefresh();
        if (LibCollections.isEmpty(blastEntities)) {
            uploadDataAdapter.setEmptyView(ViewUtils.layoutId2View(R.layout.include_no_data));
        }
        uploadDataAdapter.setNewInstance(blastEntities);
    }

    @Override
    public void addItems(List<BlastEntity> blastEntities) {
        binding.srlContent.finishLoadMore();
        if (LibCollections.isEmpty(blastEntities)) {
            binding.srlContent.finishLoadMoreWithNoMoreData();
        }
        uploadDataAdapter.addData(blastEntities);
    }

    @Override
    public void showLoading() {
        if (null == waitDialogBuilder) {
            waitDialogBuilder = new WaitDialog.Builder(getActivity()).setMessage("正在上传");
        }
        waitDialogBuilder.show();
    }

    @Override
    public void hideLoading() {
        if (null != waitDialogBuilder && waitDialogBuilder.isShowing()) {
            waitDialogBuilder.dismiss();
        }
    }
}